<script setup>
import { ref, nextTick, computed, watch } from 'vue'
import { useMusicPlayListStore } from '@/stores'
const musicPlayListStore = useMusicPlayListStore()
// import { useRouter } from 'vue-router'
// const router = useRouter()
import { useMusicCell } from '@/composables/musicCell.js'
const musicCell = useMusicCell()
// 音乐列表信息
const musicList = ref([
  // {
  //   name: '你笑起来真好看',
  //   audio_url: 'src/assets/music/154364109.mp3',
  //   singer: '程嘉敏',
  //   album: '吴少华',
  //   cover:
  //     'http://p2.music.126.net/34YW1QtKxJ_3YnX9ZzKhzw==/2946691234868155.jpg?param=300x300',
  //   // time: '01:22'
  //   rid: '',
  //   msg: '',
  // },
  // {
  //   name: '我不是你的宋冬野', // 歌名
  //   audio_url: 'src/assets/music/我不是你的宋冬野-刘大壮.mp3',
  //   singer: '等什么君', // 歌手
  //   album: '吴少华', // 专辑
  //   cover:
  //     'http://p2.music.126.net/34YW1QtKxJ_3YnX9ZzKhzw==/2946691234868155.jpg?param=300x300'
  //   // time: '04:14'
  // }
])
musicList.value = musicPlayListStore.getMusicPlayList()
// 当前播放的是哪一首歌曲
const currentIndex = ref(0)
currentIndex.value = musicPlayListStore.getMusicPlayIndex()
// 获取audio标签
const audioPlay = ref()

// 播放或暂停图标

const iconName = ref('play')

// 音乐信息卡片显示状态
// const playerInfoShow = ref(false)
// 旋转封面
const rotate = ref('paused')
// 音乐总时长
const musicTime = ref(0)
// 获取总音乐时长
const handleLoadData = () => {
  musicTime.value = audioPlay.value.duration
  console.log(audioPlay.value.duration)
}

// 之前是否在播放音乐
// const isBeforePlay = ref(false)
// 给播放按钮绑定点击事件
const playOrPaused = () => {
  clearInterval(timer)
  closeToast()
  // 等待dom更新后
  nextTick(() => {
    // 获取当前播放歌曲的audio标签的播放状态
    // 如果当前歌曲没有播放，则播放
    if (audioPlay.value.paused) {
      // 保存播放的位置
      musicPlayListStore.setMusicPlayIndex(currentIndex.value)

      audioPlay.value.play()
      // isBeforePlay.value = true
      console.log('播放')
      // 改播放图标
      iconName.value = 'pause'
      // 让音乐信息卡片显示出来
      // playerInfoShow.value = true
      //让封面旋转起来
      rotate.value = 'running'
    } else {
      // 如果当前歌曲正在播放，则暂停
      console.log('暂停')
      iconName.value = 'play'
      // isBeforePlay.value = false
      // playerInfoShow.value = false
      rotate.value = 'paused'
      audioPlay.value.pause()
    }
  })
  // console.log(audioPlay.value)
}

// 播放模式
const icoIndex = ref(0) // 0 循环播放 1 随机播放 2 单曲循环
icoIndex.value = musicPlayListStore.getMusicPlayMode()
const playModelIco = ['shunXu', 'suiJi', 'danQu']
const playModelInfo = ['循环播放', '随机播放', '单曲循环']
const playModel = () => {
  // icoIndex.value++
  // if (icoIndex.value > 2) {
  //   icoIndex.value = 0
  // }
  icoIndex.value = (icoIndex.value + 1) % 3
  musicPlayListStore.setMusicPlayMode(icoIndex.value)
  // showToast({
  //   message: playModelInfo[icoIndex.value],
  //   position: 'bottom'
  // })
  showToast(playModelInfo[icoIndex.value])
  // console.log(icoIndex.value)
}

let playedIndex = -1 // 上一首播放的索引
let waitPlayIndex = -1 // 点击上一首后，下一首歌曲的索引
// 上一首
const onPrev = () => {
  waitPlayIndex = currentIndex.value
  if (playedIndex >= 0 && icoIndex.value === 1) {
    currentIndex.value = playedIndex
    playedIndex = -1
  } else {
    // 如果当前歌曲是第一首，则播放最后一首
    if (currentIndex.value > 0) {
      currentIndex.value--
    } else {
      currentIndex.value = musicList.value.length - 1
    }
  }
  // 等待dom更新后 重新播放音乐
  // nextTick(() => {
  playOrPaused()
  // })
}
// 待播放
let waitPlay = 0
// const upWaitPlay = () => {
//   waitPlay++
// }
// 下一首
const onNext = () => {
  playedIndex = currentIndex.value
  if (waitPlayIndex >= 0 && icoIndex.value === 1) {
    currentIndex.value = waitPlayIndex
    waitPlayIndex = -1
  } else if (waitPlay > 0) {
    waitPlay--
    if (currentIndex.value < musicList.value.length - 1) {
      currentIndex.value++
    } else {
      currentIndex.value = 0
    }
  } else {
    switch (icoIndex.value) {
      case 2: // 单曲循环
      case 0:
        // 如果当前歌曲是最后一首，则播放第一首
        if (currentIndex.value < musicList.value.length - 1) {
          currentIndex.value++
        } else {
          currentIndex.value = 0
        }
        break
      case 1:
        // 随机播放
        currentIndex.value = Math.floor(Math.random() * musicList.value.length)
        break
    }
  }

  playOrPaused()
}
// 进度条时间
const musicProgress = ref(0)
// 监听 audio 标签的 timeupdate 事件 (代码写在行内)

//时间格式化函数
const formatTime = (time) => {
  // 比如：329 转换成 05:29
  // console.log(time)

  let min = parseInt(time / 60) //转换成整数   time秒单位换算
  let sec = parseInt(time % 60)
  //小于 10 的补上零
  min = min < 10 ? '0' + min : min
  sec = sec < 10 ? '0' + sec : sec

  return `${min}:${sec}`
}
// 进度条变化修改当前歌曲的播放进度
const onChange = (value) => {
  audioPlay.value.currentTime = value
}
// 开始拖拽进度条
const onDragStart = () => {
  audioPlay.value.pause()
}
// 拖拽进度条时
const upd = (value) => {
  showToast('跳转到：' + formatTime(value))
}
// 结束拖拽进度条
const onDragEnd = () => {
  audioPlay.value.currentTime = musicProgress.value
  playOrPaused()
}

// 播放列表相关
const anchors = [
  -1,
  Math.round(0.45 * window.innerHeight),
  Math.round(0.7 * window.innerHeight)
]
const height = ref(anchors[0])
const isScroll = computed(() => {
  return height.value >= 0
})
// 删除某条音乐
const delMusic = (index) => {
  if (index < currentIndex.value) {
    currentIndex.value--
  }
  if (index === currentIndex.value && musicList.value.length - 1 === index) {
    onNext()
  }
  // 如果删除的是当前播放的音乐，则播放直接播放
  musicList.value.splice(index, 1)
  if (index === currentIndex.value) {
    // onNext()
    // playOrPaused()
    nextTick(() => {
      audioPlay.value.play()
    })
  }
  musicPlayListStore.setMusicPlayList(musicList.value)
  // if (isBeforePlay.value) {
  // playOrPaused()
  // }
}
// 播放某条音乐
const playIndex = (index) => {
  audioPlay.value.pause()
  currentIndex.value = index
  playOrPaused()
}
// 插入播放列表
const insertMusic = (arr) => {
  console.log(arr)
  musicList.value.splice(currentIndex.value + waitPlay + 1, 0, ...arr)
  waitPlay += arr.length
  musicPlayListStore.setMusicPlayList(musicList.value)
}
// 清空播放列表
const setList = (arr) => {
  playOrPaused()
  musicList.value = arr
  musicPlayListStore.setMusicPlayList(musicList.value)
}
// 打开播放列表并定位到正在播放
const playing = ref()
const showList = ref(false)
const onOpenList = () => {
  showList.value = true
  nextTick(() => {
    if (musicList.value.length < 5) {
      height.value = anchors[1]
    } else {
      height.value = anchors[2]
    }
    // console.log(list.value, playing.value)
  })
  nextTick(() => {
    playing.value[0].scrollIntoView({
      behavior: 'instant',
      // behavior: 'smooth',
      block: 'center'
      // block: 'end'
    })
  })
}
const onCloseList = () => {
  height.value = anchors[0]
  // showList.value = false
}
watch(height, (newValue) => {
  if (newValue === -1) {
    showList.value = false
  }
})
// 处理音乐播放错误
let timer = null
const errToast = () => {
  clearInterval(timer)
  const toast = showToast({
    duration: 0,
    message: '服务异常 3 秒后播放下一首'
  })

  let second = 3
  timer = setInterval(() => {
    second--
    if (second) {
      toast.message = `服务异常 ${second} 秒后播放下一首`
    } else {
      clearInterval(timer)
      closeToast()
      onNext()
    }
  }, 1000)
}
// const musicError = () => {
//   // showFailToast('服务异常')
//   if (musicList.value[currentIndex.value].rid >= 20) {
//     getKWMusicService(musicList.value[currentIndex.value].rid)
//       .then((res) => {
//         musicList.value[currentIndex.value].audio_url = res.data
//         nextTick(() => {
//           audioPlay.value.currentTime = musicProgress.value
//         })
//         playOrPaused()
//         return
//       })
//       .catch(() => {
//         errToast()
//       })
//   } else {
//     getWYYMusicService({
//       rid: musicList.value[currentIndex.value].rid,
//       msg: musicList.value[currentIndex.value].msg
//     })
//       .then((res) => {
//         musicList.value[currentIndex.value].audio_url = res.data.mp3
//         nextTick(() => {
//           audioPlay.value.currentTime = musicProgress.value
//         })
//         playOrPaused()
//         return
//       })
//       .catch(() => {
//         errToast()
//       })
//   }
//   errToast()
// }
const musicError = async () => {
  try {
    const music = await musicCell.getMusic(musicList.value[currentIndex.value])
    musicList.value[currentIndex.value] = music
    nextTick(() => {
      audioPlay.value.currentTime = musicProgress.value
    })
    playOrPaused()
  } catch (err) {
    errToast()
  }
}

// 显示或隐藏播放器
const showPlayer = ref(false)
const showMusicPlayer = () => {
  showPlayer.value = !showPlayer.value
  if (!showPlayer.value) {
    onCloseList()
  }
  clearInterval(timer)
  // router.push('/home')
}

// 更多
const moreModeRef = ref(null)
const onShowMore = (item) => {
  moreModeRef.value.showMoreMode()
  moreModeRef.value.initInfo({ ...item })
}

// 导出
defineExpose({
  formatTime, //时间格式化函数
  showMusicPlayer, //是否显示播放器
  onNext,
  insertMusic, // 插入播放列表
  // upWaitPlay, // 等待播放的音乐
  setList,
  audioPlay,
  playOrPaused
})
</script>
<template>
  <transition name="music-player-fixed">
    <div v-show="showPlayer" class="music-player-fixed">
      <!-- 音乐播放器 -->
      <div class="player-warp">
        <!-- 歌曲信息卡片 -->
        <div class="player-info" v-if="musicList.length > 0">
          <!-- :class="{ show: playerInfoShow }" -->
          <div class="info">
            <div class="name">
              {{ musicList[currentIndex]?.name || '未知歌曲' }}
            </div>
            <div class="singer-album" :key="showPlayer">
              <van-notice-bar
                style="
                  width: 100%;
                  padding: 0;
                  margin: 0;
                  height: 20px;
                  line-height: 20px;
                  color: inherit;
                  background: inherit;
                "
                :key="musicList[currentIndex].audio_url"
              >
                {{
                  `${musicList[currentIndex]?.singer || '未知'}${musicList[currentIndex]?.album ? ' - ' + musicList[currentIndex]?.album : ''}`
                }}
              </van-notice-bar>
            </div>
            <!-- 进度条 -->
            <div class="music_progress">
              <div class="music_progress-top">
                <span class="current-time">{{
                  formatTime(musicProgress || 0)
                }}</span>
                <span class="time">{{ formatTime(musicTime || 0) }}</span>
              </div>
              <!-- 进度条%比 -->
              <!-- <div class="music_progress-bar">
            <div class="music_progress-line"></div>
          </div> -->
              <van-slider
                @drag-start="onDragStart"
                @drag-end="onDragEnd"
                @change="onChange"
                @update:model-value="upd"
                button-size="10"
                bar-height="3"
                v-model="musicProgress"
                :min="0"
                :max="musicTime"
              />
            </div>
          </div>
        </div>
        <!-- 音乐控制器 -->
        <div class="player-control">
          <!-- 封面唱片 -->
          <div class="cover" :style="{ 'animation-play-state': rotate }">
            <img
              :src="musicList[currentIndex].cover"
              v-if="musicList.length > 0"
              alt="封面唱片"
              @click.stop="onShowMore(musicList[currentIndex])"
            />
          </div>
          <!-- 控制按钮 -->
          <div class="control">
            <!-- 播放模式 -->
            <i id="playBtn">
              <van-icon
                @click="playModel()"
                class-prefix="my-icon"
                :name="playModelIco[icoIndex]"
              />
            </i>
            <!-- 上一首 -->
            <i id="prevBtn">
              <!-- <van-icon name="arrow-left" /> -->
              <van-icon @click="onPrev()" class-prefix="my-icon" name="prev" />
            </i>
            <!-- 播放暂停 -->
            <i id="playBtn">
              <van-icon @click="playOrPaused()" :name="iconName" />
            </i>
            <!-- 下一首 -->
            <i id="nextBtn">
              <!-- <van-icon name="arrow" /> -->
              <van-icon @click="onNext()" class-prefix="my-icon" name="next" />
            </i>
            <!-- 音乐列表 -->
            <i id="openModal">
              <!-- , (isScroll = true) -->
              <van-icon name="wap-nav" @click="onOpenList()" />
            </i>
          </div>
        </div>
        <!-- 通过 class-prefix 指定类名为 my-icon -->
      </div>
      <MoreMode ref="moreModeRef"></MoreMode>
      <!-- :key="currentIndex" -->
      <audio
        ref="audioPlay"
        @ended="icoIndex === 2 ? playOrPaused() : onNext()"
        @loadedmetadata="handleLoadData()"
        @timeupdate="musicProgress = audioPlay.currentTime"
        @error="musicError()"
        :src="musicList[currentIndex].audio_url"
        :key="musicList[currentIndex].audio_url"
        v-if="musicList.length > 0"
        :autoplay="false"
      ></audio>
    </div>
  </transition>
  <van-overlay
    :show="showList"
    @click.self="onCloseList()"
    z-index="999"
    :lock-scroll="false"
  >
    <!-- :key="musicList.length" -->
    <van-floating-panel
      :lock-scroll="isScroll"
      safe-area-inset-bottom
      v-model:height="height"
      :anchors="anchors"
    >
      <template #header>
        <div class="head">
          <h3>播放列表</h3>
          <span style="font-size: 14px; color: #9f9c9c">
            ({{ musicList.length }})
          </span>
          <div class="middle"></div>
          <i>
            <!-- , (isScroll = false) -->
            <van-icon name="cross" @click.stop="onCloseList()" size="18px" />
          </i>
        </div>
        <div class="operate">
          <van-icon @click.stop="setList([])" name="delete-o" size="18" />
        </div>
      </template>
      <!-- 列表 -->
      <template #default>
        <!-- :title="item.name + ' - ' + item.singer"
      :title-class="{ active: currentIndex === index }"
      :icon="currentIndex === index ? 'shop-o' : ''" -->
        <van-cell
          v-for="(item, index) in musicList"
          :key="index"
          @click.stop="playIndex(index)"
        >
          <!-- 使用 title 插槽来自定义标题 -->
          <template #title>
            <span
              :class="{ active: currentIndex === index }"
              style="padding-right: 5px"
            >
              {{ item.name || '未知歌曲' }} - {{ item.singer || '' }}
            </span>
            <van-tag v-if="currentIndex === index" type="primary">
              <div ref="playing">正在播放</div>
            </van-tag>
          </template>
          <!-- 使用 right-icon 插槽来自定义右侧删除图标 -->
          <template #right-icon>
            <van-icon name="cross" @click.stop="delMusic(index)" />
          </template>
        </van-cell>
        <div class="bottom">没有更多了</div>
      </template>
    </van-floating-panel>
  </van-overlay>
</template>
<style scoped>
/* .body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  /* flex-direction: column; 
  background-color: #b3b0b0;
  /* user-select: none; 
} */
.music-player-fixed {
  position: fixed;
  bottom: 50px;
  width: 100%;
}
.music-player-fixed-enter-active,
.music-player-fixed-leave-active {
  transition: opacity 0.5s ease;
}

.music-player-fixed-enter-from,
.music-player-fixed-leave-to {
  opacity: 0;
}
.player-warp {
  position: relative;
}
/* 音乐控制器开始 */
.player-warp .player-control {
  background-color: #3d4762;
  width: 100%;
  height: 70px;
  border-radius: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  z-index: 10;
}
.player-control .cover {
  width: 100px;
  height: 100px;
  margin-top: -60px;
  background-color: #fff;
  border-radius: 50%;
  padding: 6px;
  position: relative;
  /* 动画 */
  animation: zhuan 5s infinite linear;
  animation-play-state: paused; /* paused 停止动画，running 动画开始 */
}
/* 动画 */
@keyframes zhuan {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 使用伪元素定位封面白点 */
.player-control .cover::before {
  content: '';
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: #fff;
  transform: translate(-50%, -50%);
}
.player-control .cover img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

/* 控制按钮 */
.control {
  width: 60%;
  display: flex;
  align-content: space-between;
  justify-content: center;
}
.control i {
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-size: 26px;
  color: #b3b0b0;
  cursor: pointer; /* 鼠标小手 */
  transition: all 0.4s; /* 过度效果 */
}
.control i:hover {
  border-radius: 6px;
  background-color: rgba(71, 70, 70, 0.2);
  color: #fff;
}

/* 歌曲信息卡片 */
.player-info {
  width: 90%;
  position: absolute;
  top: -115%;
  /* top: 0%; */
  left: 50%;
  padding: 10px;
  background: #b3c2d0;
  transform: translate(-50%);
  z-index: 0;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37); /* 阴影 */
  /* backdrop-filter: blur(3.5px); */
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  display: flex;
  justify-content: flex-end;
  /* opacity: 0; */
  opacity: 1;
  /* transition:
    top 0.3s ease-in-out,
    opacity 0.3s ease-in-out; */
}
/* 用于音乐信息卡片显示 */
/* .show {
  top: -115%;
  opacity: 1;
} */

.player-info .info {
  width: 65%;
  font-size: 15px;
}
.info .name {
  font-size: 15px;
  font-weight: bold;
}
.info .singer-album {
  color: #757474;
  line-height: 20px;
  /*white-space: nowrap; /* 不换行 */
  /*overflow: hidden; /* 隐藏超出的内容 */
  /*text-overflow: ellipsis; /* 超出的部分用省略号表示 */
}
/* 进度条%比 */
.info .music_progress {
  width: 100%;
}
.music_progress .music_progress-top {
  display: flex;
  justify-content: space-between;
  color: #757474;
  line-height: 20px;
  margin-bottom: 3px;
}
.music_progress .music_progress-bar {
  width: 100%;
  height: 3px;
  background-color: #cccaca;
  border-radius: 10px;
  margin-top: 3px;
}
.music_progress-bar .music_progress-line {
  width: 0%;
  height: 100%;
  background-color: blue;
}
/* 播放列表相关 */
.head {
  padding-left: 10px;
  padding-right: 22px;
  line-height: 55px;
  display: flex;
  align-content: space-between;
  justify-content: space-between;
  text-align: center;
}
.head .middle {
  /* padding: 2px, 4px, 6px, 8px; */
  margin: auto;
  width: 80px;
  height: 4px;
  background-color: #cccaca;
  border-radius: 10px;
  text-align: center;
}
/* 中间操作相关 */
.operate {
  padding-bottom: 12px;
  padding-right: 15px;
  text-align: right;
  border-bottom: 1px solid #e7e5e5;
}
/* 底部占位 */
.bottom {
  height: 80px;
  text-align: center;
  line-height: 80px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.4);
}
/* 正在播放的项 */
::v-deep .van-cell .active {
  color: #7ccffa;
}
</style>
